package com.example.weight;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.householdWaste.AbnormalRubbishActivity;
import com.example.weight.model.Station;
import com.example.weight.navigation.FactoryActivity;
import com.example.weight.navigation.MainNavigationActivity;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.IncomingSceneMix;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.OutcomingSceneInsectSeparate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences preferences;

    private ItemAdapter adapter;
    private List<String> nameList;
    private List<Station> stationList;
    private EditText loginName, password;

    private PopupWindow popupWindow;

//    private String factory = "station1", factory1;

//    private Handler handler = new Handler(){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//            loginName.setText("test"+msg.obj.toString());
//        }
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        stationList = new ArrayList<>();
        loginName = findViewById(R.id.login_name);
        password = findViewById(R.id.login_pwd);


//        System.out.println(factory);


//        Uri uri = Uri.parse("浏览器地址");
//        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);

//        Spinner station = findViewById(R.id.login_station);
//        station.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                String[] posts = getResources().getStringArray(R.array.post);
//                post = posts[position];
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });

        Button button = findViewById(R.id.login_button);
        button.setOnClickListener(v -> {
            SharedPreferences.Editor editor = preferences.edit();
            // 若有进行删除操作，更新nameList
            List<Item> tempItemList = adapter.getList();
            if (tempItemList.size() != nameList.size()) {
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 判断该输入框内容是否已存在，不存在则加入
            String currentCheckResult = loginName.getText().toString();
            if (!currentCheckResult.equals("") && !nameList.contains(currentCheckResult)) {
                nameList.add(currentCheckResult);
            }

            editor.putStringSet("login-name", new HashSet<>(nameList));
            editor.apply();

//            String name = "admin";
            String name = loginName.getText().toString();
            String password1 = password.getText().toString();
            if (name.equals("")) {
                Toast.makeText(MainActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
                return;
            }

            // 以下三行在登录验证完成后注释
//            Intent intent = new Intent(MainActivity.this, MainNavigationActivity.class);
//            intent.putExtra("name", name);
//            intent.putExtra("permissionLevel", "管理员");
//            startActivity(intent);
//            getData();


//            Config.setUrl("");
//            Config.setUrl("http://39.105.183.48:8090");

            // 添加登录验证
            RequestQueue queue = Volley.newRequestQueue(this);

            String url = Config.url + "/user/login0";
            StringRequest setSysNameRequest = new StringRequest(Request.Method.POST, url,
                    new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (!jsonObject.isNull("data")) {
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    Log.d("data", data.toString());

                                    JSONArray recordlist = data.getJSONArray("factory");
                                    Log.d("data", recordlist.toString());

                                    if(recordlist.length()>0) {
                                        stationList.clear();
                                        for (int i = 0; i < recordlist.length(); i++) {
                                            JSONObject record = recordlist.getJSONObject(i);
                                            stationList.add(new Station(0, record.getString("name"), record.getString("factory"), " "));
                                        }
                                    }

                                    Intent intent = new Intent(MainActivity.this, FactoryActivity.class);

                                    Bundle bundle = new Bundle();
                                    bundle.putString("name",name);
                                    bundle.putString("password", password1);
                                    bundle.putSerializable("stationList", (Serializable) stationList);
                                    //把对应用户的场站信息存入下一页
                                    intent.putExtras(bundle);

                                    startActivity(intent);
                                } else {
                                    Toast.makeText(MainActivity.this,
                                            "用户名或密码错误", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", loginName.getText().toString());
                    map.put("password", password.getText().toString());
                    return map;
                }
            };
            setSysNameRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(setSysNameRequest);
        });

        // 设置输入记录缓存
        preferences = getSharedPreferences("login", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("login-name", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
        ListView listView = new ListView(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (adapter.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter.getList();
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = nameList.get(position);
            loginName.setText(result);
            popupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 10;
        // 参数为 1.View 2.宽度 3.高度
        popupWindow = new PopupWindow(listView, width, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置点击外部区域可以取消popupWindow
        popupWindow.setOutsideTouchable(true);

        loginName.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                popupWindow.showAsDropDown(loginName);
            }
        });
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }


//    private OkHttpClient client = new OkHttpClient();
//
//    public String get(String url) throws IOException {
//        Request request = new Request.Builder()
//                .url(url)
//                .build();
//        Response response = client.newCall(request).execute();
//        return response.body().string();
//    }
//
//    public String post(String url) throws IOException {
//        RequestBody body = new FormBody.Builder()
//                .add("equipmentName", "液压步进式给料机")
//                .add("maintenanceContent", "固定轴承")
//                .build();
//        Request request = new Request.Builder()
//                .url(url)
//                .post(body)
//                .build();
//        Response response = client.newCall(request).execute();
//        return response.body().string();
//    }
//
//    private void getData() {
//        Log.d("zys", "in getData");
//        new Thread(){
//            @Override
//            public void run() {
//                Log.d("zys", "in run");
//                super.run();
//                try {
//                    Log.d("zys", "in try");
////                    String result = get("http://r36qha.natappfree.cc/kitchenwaste/discharge/get");
//                    String result = post("http://r36qha.natappfree.cc//shlj/equipmentMaintenance/getlatest");
//                    if (result.equals(""))
//                        Log.d("zys", "wei kong");
//                    Log.d("zys", result);
//                    JSONObject object = new JSONObject(result);
//                    JSONObject data = object.getJSONObject("data");
//                    String id = data.getString("remarks");
//                    Message msg = Message.obtain();
//                    msg.obj = id;
//                    handler.sendMessage(msg);
//                } catch (IOException | JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//    }
}
